package site.qjdb.controller;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import site.qjdb.constant.Info;
import site.qjdb.pojo.Cart;
import site.qjdb.pojo.Goods;
import site.qjdb.pojo.User;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.service.CartService;
import site.qjdb.service.GoodsService;
import site.qjdb.service.UserService;
import site.qjdb.util.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
	@Resource
	private CartService cartService;
	@Resource
	private GoodsService goodsService;
	@Resource
	private UserService userService;
	
	/**
	 * 	添加进购物车
	 * 	gid：商品id，必填
	 * 	count：购买数量，必填
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Object add(@RequestParam("id") String gid,
			@RequestParam String count,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		// 校验count
		Integer countInteger = null;
		try {
			countInteger = Integer.parseInt(count);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.ILLEGAL_NUMBER);
		}
		// 校验gid
		Integer gidInteger = null;
		try {
			gidInteger = Integer.parseInt(gid);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 根据gid查找Goods，查看状态是否为1（通过）
		Goods _goods = new Goods();
		_goods.setGid(gidInteger);
		_goods.setState(1);
		Goods newGoods = goodsService.findGoods(_goods);
		if(newGoods == null) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 查找购物车内是否已有此商品，若购物车数量+count > 商品总数量则不能加入购物车
		Cart _cart = new Cart();
		_cart.setGoods(_goods);
		_cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		_cart.setIsDel(0);
		List<Cart> cartList = cartService.findCartAll(_cart);
		if(cartList != null) {
			Cart newCart = cartList.get(0);
			Integer newCartCount = newCart.getCount();
			if(((newCartCount + countInteger) > (newGoods.getCount() - newGoods.getReservedCount())) || (countInteger < 1)){
				return new CommonResult<>(ResponseCode.CART_EXIST);
			} else {
				// 设置购物车内新的购买数量
				_cart.setCount(newCartCount + countInteger);
				// 设置购物车项id
				_cart.setCartId(newCart.getCartId());
				cartService.modifyCart(_cart);
			}
		} else {
			// 校验count
			int goodsCount = newGoods.getCount();
			int goodsReservedCount = newGoods.getReservedCount();
			if(countInteger > (goodsCount - goodsReservedCount) || (countInteger < 1)) {
				return new CommonResult<>(ResponseCode.ILLEGAL_NUMBER);
			}
			Cart cart = new Cart();
			// 设置用户id
			cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
			// 设置gid
			Goods goods = new Goods();
			goods.setGid(gidInteger);
			cart.setGoods(goods);
			// 设置购买数量
			cart.setCount(countInteger);
			// 设置小计
			cart.setDbSubtotal(newGoods.getDbPrice() * countInteger);
			// 设置是否删除
			cart.setIsDel(0);
			// 设置时间
			cart.setTime(new Date());
			cartService.addCart(cart);
		}
		return new CommonResult<>(ResponseCode.SUCCESS);
	}
	
/*	/**
	 * 	查询实际购物车项数量，已下架商品也可以查到
	 * 
	 * *//*
	@ResponseBody
	@RequestMapping(value = "/count", method = RequestMethod.POST)
	public Object count(HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		Cart cart = new Cart();
		cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		cart.setIsDel(0);
		int count = cartService.findCartCount(cart);
		return new CommonResult<>(ResponseCode.SUCCESS, count);
	}*/
	
	/**
	 * 	查看我的购物车
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/myCart", method=RequestMethod.POST)
	public Object myCart(HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		Cart cart = new Cart();
		cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		cart.setIsDel(0);
		List<Cart> cartList = cartService.findCartAll(cart);
		return new CommonResult<>(ResponseCode.SUCCESS, cartList);
	}
	
	/**
	 * 	删除购物车项，单项删除
	 * 	cartId：购物车项id，必传
	 * 	gid：对应商品id，必传
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Object delete(@RequestParam("id1") String cartId,
			@RequestParam("id2") String gid,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		Integer cartIdInteger = null;
		Integer gidInteger = null;
		try {
			cartIdInteger = Integer.parseInt(cartId);
			gidInteger = Integer.parseInt(gid);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		Cart cart = new Cart();
		// 设置cartId
		cart.setCartId(cartIdInteger);
		// 设置uid
		cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		// 设置Goods
		Goods goods = new Goods();
		goods.setGid(gidInteger);
		cart.setGoods(goods);
		boolean flag = cartService.deleteCart(cart);
		if(flag) {
			return new CommonResult<>(ResponseCode.SUCCESS);
		} else {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
	}
	
	/**
	 * 	删除购物车项，多项删除
	 * 	params：参数
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/deletes", method = RequestMethod.POST)
	public Object deletes(@RequestParam String param,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		List<Cart> cartList = new ArrayList<>();
		try {
			String[] params = param.split("\\$");
			for(String p : params) {
				String gid = p.split("#")[0];
				String cartId = p.split("#")[1];
				Integer gidInteger = Integer.parseInt(gid);
				Integer cartIdInteger = Integer.parseInt(cartId);
				Cart cart = new Cart();
				// 设置cartId
				cart.setCartId(cartIdInteger);
				// 设置uid
				cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
				// 设置Goods
				Goods goods = new Goods();
				goods.setGid(gidInteger);
				cart.setGoods(goods);
				cartList.add(cart);
			}	
			cartService.deleteCarts(cartList);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		return new CommonResult<>(ResponseCode.SUCCESS);
	}
	
	/**
	 * 	对购物车内商品数量进行增加和减少操作
	 * 	cartId：购物车项id，必传
	 * 	gid：购物车内商品id，必传
	 * 	type：判断是增加操作还是删除操作。0：减少，1：增加
	 * */
	@ResponseBody
	@RequestMapping(value = "/amount", method=RequestMethod.POST)
	public Object amount(@RequestParam("id1") String cartId,
			@RequestParam("id2") String gid,
			@RequestParam String type,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		if(!("1".equals(type) || "0".equals(type))) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		Integer cartIdInteger = null;
		Integer gidInteger = null;
		try {
			cartIdInteger = Integer.parseInt(cartId);
			gidInteger = Integer.parseInt(gid);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 根据gid查找Goods，查看有没有下架
		Goods _goods = new Goods();
		_goods.setState(1);
		_goods.setGid(gidInteger);
		if(goodsService.findGoods(_goods) == null) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 查找Cart，获得count
		Cart _cart = new Cart();
		// 设置uid
		_cart.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		// 设置cartId
		_cart.setCartId(cartIdInteger);
		// 设置gid
		Goods goods = new Goods();
		goods.setGid(gidInteger);
		_cart.setGoods(goods);
		// 设置未删除
		_cart.setIsDel(0);
		List<Cart> cartList = cartService.findCartAll(_cart);
		if(cartList == null) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 获得购物车项
		Cart newCart = cartList.get(0);
		// 设置count
		int newCartCount = 0;
		if("1".equals(type)) {
			newCartCount = newCart.getCount() + 1; 
		} else if("0".equals(type)) {
			newCartCount = newCart.getCount() - 1; 
		}
		int goodsCount = newCart.getGoods().getCount();
		int goodsReservedCount = newCart.getGoods().getReservedCount();
		if(newCartCount > (goodsCount - goodsReservedCount) || newCartCount < 1) {
			return new CommonResult<>(ResponseCode.ILLEGAL_NUMBER);
		}
		Cart cart = new Cart();
		// 设置新的购物车内商品的数量
		cart.setCount(newCartCount);
		// 设置购物车项id
		cart.setCartId(cartIdInteger);
		// 设置小计
		cart.setDbSubtotal(newCart.getGoods().getDbPrice() * newCartCount);
		cartService.modifyCart(cart);
		return new CommonResult<>(ResponseCode.SUCCESS);
	}
}
